<template>
    <div class="mycontainer">
        <div class="buttonarea" v-show="!isCloseSide">
            <div style="text-align: center;">
                <img :src=lefticon class="icon-img" @click="closeSidebar">
            </div>
            <button @click="formatJson" class="tool-button">格式化</button>
            <button @click="forexample" class="tool-button">示 例</button>

            <!-- 主题下拉菜单 -->
            <div class="dropdown">
                <button class="dropdown-button" @click="toggleDropdown">
                    {{ selectedTheme }}
                    <span class="arrow"></span>
                </button>
                <ul v-if="isOpen" class="dropdown-menu">
                    <li v-for="(option, index) in options" :key="index"
                        :class="{ 'highlight': option.name === selectedTheme }" @click="selectOption(option)">
                        {{ option.name }}
                    </li>
                </ul>
            </div>

            <button @click="copyJson" class="tool-button">复 制</button>
        </div>
        <div class="input-container">
            <textarea class="input-textarea" v-model="inputJson" placeholder="请输入JSON字符串" rows="10"
                @input="handleInput"></textarea>
            <!-- <button @click="formatJson">格式化</button> -->
        </div>
        <div class="output-container">
            <pre><code class="json" :class="selectedHighlightStyle" v-html="formattedJson"></code></pre>
            <!-- <button v-if="isShowCopy" @click="copyJson">复制</button> -->
        </div>
    </div>
</template>

<script>
import hljs from 'highlight.js';
import 'highlight.js/styles/idea.css';

export default {
    data() {
        return {
            inputJson: '',
            formattedJson: '',
            formattedJsonText: '',
            lefticon: require('@/assets/icons/mtileft.png'),
            righticon: require('@/assets/icons/mtiright.png'),
            isCloseSide: false,
            options: [{ name: 'idea', value: 'idea' },
            { name: 'VS', value: 'vs' },
            { name: 'Git', value: 'github' },
            { name: 'gml', value: 'gml' },
            { name: 'far', value: 'far' },
            { name: 'dark', value: 'dark' },
            { name: 'monika', value: 'monika' },
            ],
            selectedTheme: 'idea',
            isOpen: false,
            props: ['isCloseSide']
        };
    },
    methods: {
        handleInput() {
            this.formatJson();
        },
        formatJson() {
            try {
                const json = JSON.parse(this.inputJson);
                this.formattedJson = hljs.highlight(JSON.stringify(json, null, 2), { language: 'json' }).value;
                //this.changeTheme(this.selectedTheme);
            } catch (e) {
                this.formattedJson = '<span style="color: red;">无效的JSON字符串\n</span>' + e;
            }
        },
        copyJson() {
            // 使用 navigator.clipboard API 直接复制纯文本
            navigator.clipboard.writeText(this.formattedJson).then(() => {
                this.$toast('已复制到剪贴板!', 1000, 50);
            }, (err) => {
                console.error('复制失败:', err);
                this.$toast('复制失败，请重试!', 1000, 50);
            });
        },
        closeSidebar() {
            this.isCloseSide = true;
        },
        forexample() {
            this.inputJson = '{"title":"JSON在线解析","json.url":"https://www.json.cn","keywords":"JSON在线解析","功能":["JSON美化","JSON数据类型显示","JSON数组显示角标","高亮显示","错误提示","\u003e","&nbsp;"," ","<h1>JSON在线解析</h1>",{"备注":["www.json.cn","json.cn"]}],"加入我们":{"QQ群":661275469},"特殊符号":["&currency","&timestamp","&region","&params","&lt;&lt;sane&gt;&gt;","gbk -> utf-8","gbk -> utf-8"],"numbers":[305667554401374209,103248655202358790,123456789012345679,987654321098765432,246813579246813579,135792468013579246,864209864209864209,123456789098765432,987654321012345679,246813579135792468],"id2":22022621134265013,"BigNumber":71357798191653192098,"content":"永和九年，岁在癸丑，暮春之初，会于会稽山阴之兰亭，修禊事也。群贤毕至，少长咸集。此地有崇山峻岭，茂林修竹，又有清流激湍，映带左右，引以为流觞曲水，列坐其次。虽无丝竹管弦之盛，一觞一咏，亦足以畅叙幽情。是日也，天朗气清，惠风和畅。仰观宇宙之大，俯察品类之盛，所以游目骋怀，足以极视听之娱，信可乐也。夫人之相与，俯仰一世。或取诸怀抱，悟言一室之内；或因寄所托，放浪形骸之外。虽趣舍万殊，静躁不同，当其欣于所遇，暂得于己，快然自足，不知老之将至；及其所之既倦，情随事迁，感慨系之矣。向之所欣，俯仰之间，已为陈迹，犹不能不以之兴怀，况修短随化，终期于尽！古人云：“死生亦大矣。”岂不痛哉！每览昔人兴感之由，若合一契，未尝不临文嗟悼，不能喻之于怀。固知一死生为虚诞，齐彭殇为妄作。后之视今，亦犹今之视昔，悲夫！故列叙时人，录其所述，虽世殊事异，所以兴怀，其致一也。后之览者，亦将有感于斯文。"}'
            this.formatJson()
        },
        toggleDropdown() {
            this.isOpen = !this.isOpen;
        },
        selectOption(option) {
            this.selectedTheme = option.name;
            this.isOpen = false;
            this.changeTheme(option.value);
        },
        changeTheme(themeName) {
            if (this.inputJson) {
                // 移除旧的样式表
                let oldLinkElement = document.querySelector('link[rel="stylesheet"][href*="highlight.js"]');
                if (oldLinkElement) {
                    oldLinkElement.remove();
                }

                // 加载新的样式表
                let linkElement = document.createElement("link");
                linkElement.rel = "stylesheet";
                linkElement.href = `https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/${themeName}.min.css`;
                document.head.appendChild(linkElement);

                // 重新高亮代码
                hljs.highlightAll();
            }
            else{
                this.formattedJson = '<span style="color: red;">请先输入原始JSON\n</span>';
            }

        },

    }
};
</script>

<style scoped>
.mycontainer {
    display: flex;
    height: 100%;
    overflow: hidden;
}

.buttonarea {
    display: flex;
    flex-direction: column;
    background-color: #ffffff;
    border-radius: 20px;
    width: 100px;
    height: 50%;
    align-items: center;
}

.icon-img {
    margin-top: 20px;
}

.tool-button {
    margin-top: 20px;
    display: flex;
    width: 80px;
    text-align: center;
    justify-content: center;
    /* 水平居中 */
    align-items: center;
    /* 垂直居中 */
    height: 40px;

}

.input-container {
    margin-left: 10px;
    width: 40%;
    display: flex;
    flex-direction: column;
}

.output-container {
    width: 60%;
    margin-left: 10px;
    display: flex;
    flex-direction: column;
    border-radius: 20px;
}


textarea {
    flex: 1;
    padding: 10px;
    border: none;
    resize: none;
    outline: none;
    overflow-x: auto;
    overflow-wrap: break-word;
    word-wrap: break-word;
    white-space: pre-wrap;
    border-radius: 20px;
}

button {
    margin-top: 10px;
    padding: 10px;
    width: 120px;
    background-color: #007aff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background-color: #0056b3;
}

pre {
    margin: 0;
    padding: 10px;
    border-radius: 20px;
    overflow-x: auto;
    background-color: #fff;
    height: 100%;
}

code {
    font-family: 'Consolas', 'Times New Roman', Courier, monospace;
    font-size: 12px;
    font-style: italic;
    font-weight: bold;
    white-space: pre-wrap;
    word-wrap: break-word;
    /* 自动换行 */
    overflow-wrap: break-word;
    /* 自动换行 */
    overflow-x: auto;
    /* 添加横向滚动条 */
}

.dropdown {
    position: relative;
    display: inline-block;
    width: 80px;
}

.dropdown-button {
    background-color: #007aff;
    color: white;
    padding: 10px;
    border: none;
    cursor: pointer;
    border-radius: 4px;
    width: 80px;
    margin-top: 20px;
}

.arrow {
    display: inline-block;
    width: 0;
    height: 0;
    margin-left: 10px;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 5px solid white;
}

.dropdown-menu {
    position: absolute;
    background-color: white;
    border: 1px solid #ccc;
    border-radius: 4px;
    width: 100%;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
    z-index: 1000;
    list-style: none;
    padding: 0;
    margin: 0;
    top: 100%;
    left: 0;
}

.dropdown-menu li {
    padding: 10px;
    cursor: pointer;
}

.dropdown-menu li:hover {
    background-color: #f0f0f0;
}

.highlight {
    background-color: #007aff;
    color: white;
}
</style>